package com.yc.star.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.star.entity.Talkmsg;
import com.yc.star.entity.User;
import com.yc.star.mapper.TalkmsgMapper;
import com.yc.star.vo.RedisUtil;
import com.yc.star.vo.Result;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/chat")
public class ChatDo {

    @Resource
    RedisUtil redisUtil;

    @Resource
    TalkmsgMapper talkmsgMapper;


    @RequestMapping("friendRequest")
    public Result friendRequest(Long requesterId, HttpServletRequest request) {
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        //存到哪?

        return null;
    }

    @RequestMapping("savemsg")
    public Result saveMsg(@RequestBody Talkmsg talkmsg) {
        System.out.println(talkmsg);
        talkmsgMapper.insert(talkmsg);
        return null;
    }

    @RequestMapping("getMsgRecord")
    public Result getMsgRecord(String receiveid, String senderid) {
        System.out.println(receiveid);
        System.out.println(senderid);
        LambdaQueryWrapper<Talkmsg> lqw = new LambdaQueryWrapper();

        lqw.eq(Talkmsg::getSendid,senderid)
                .eq(Talkmsg::getReceiveid, receiveid)
                .or()
                .eq(Talkmsg::getReceiveid, senderid)
                .eq(Talkmsg::getSendid, receiveid)
                .orderByAsc(Talkmsg::getCreateTime);
        List<Talkmsg> talkmsgs = talkmsgMapper.selectList(lqw);
        List<User> userRedis = (List<User>) redisUtil.get("userRedis");
        for (Talkmsg talkmsg:talkmsgs){
            for (User user:userRedis){
                boolean senderMatched = false;
                boolean receiverMatched = false;

                // 检查是否匹配发件人
                if (talkmsg.getSendid().equals(user.getId())) {
                    talkmsg.setSendername(user.getUsername());
                    talkmsg.setSenderimg(user.getAvatarUrl());
                    senderMatched = true;
                }
                // 检查是否匹配收件人
                if (talkmsg.getReceiveid().equals(user.getId())) {
                    talkmsg.setReceivename(user.getUsername());
                    talkmsg.setReceiveimg(user.getAvatarUrl());
                    receiverMatched = true;
                }
                // 如果两个条件都满足，退出内层循环
                if (senderMatched && receiverMatched) {
                    break;
                }
            }
        }
        System.out.println(talkmsgs);
        return new Result(1,"Success",talkmsgs);
    }
}
